from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings
from api.models.vip import VipPackage, VipOrder, VipActivationCode, VipMember
from api.models import WechatUser
from adminapi.utils.jwt_utils import verify_token
from adminapi.utils.response import success_response, error_response
from adminapi.utils.pagination import paginate_queryset
from adminapi.utils.log_utils import log_operation
import json
from datetime import datetime, timedelta
from django.utils import timezone
from django.contrib.auth.models import User

@require_http_methods(["GET"])
def vip_package_list(request):
    """获取VIP套餐列表"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        
        # 获取套餐列表
        queryset = VipPackage.objects.filter(is_active=True).order_by('price')
        result = paginate_queryset(queryset, page, size)
        
        # 格式化数据
        package_list = [package.to_dict() for package in result['items']]
        
        return success_response({
            'list': package_list,
            'total': result['total'],
            'page': result['page'],
            'size': result['size'],
            'pages': result['pages']
        })
    except Exception as e:
        return error_response(f'获取VIP套餐列表失败：{str(e)}')

@csrf_exempt
@require_http_methods(["POST"])
def vip_package_create(request):
    """创建VIP套餐"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 解析请求数据
        data = json.loads(request.body)
        name = data.get('name')
        price = data.get('price')
        duration = data.get('duration')
        description = data.get('description')
        
        if not all([name, price, duration, description]):
            return error_response('参数不完整', 400)
        
        # 创建套餐
        package = VipPackage.objects.create(
            name=name,
            price=price,
            duration=duration,
            description=description
        )
        
        # 记录操作日志
        log_operation(admin_id, 'create_vip_package', f'创建VIP套餐：{package.name}')
        
        return success_response(package.to_dict())
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'创建VIP套餐失败：{str(e)}')

@csrf_exempt
@require_http_methods(["PUT"])
def vip_package_update(request, package_id):
    """更新VIP套餐"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找套餐
        try:
            package = VipPackage.objects.get(id=package_id)
        except VipPackage.DoesNotExist:
            return error_response('未找到指定的套餐', 404)
        
        # 解析请求数据
        data = json.loads(request.body)
        package.name = data.get('name', package.name)
        package.price = data.get('price', package.price)
        package.duration = data.get('duration', package.duration)
        package.description = data.get('description', package.description)
        package.is_active = data.get('is_active', package.is_active)
        package.save()
        
        # 记录操作日志
        log_operation(admin_id, 'update_vip_package', f'更新VIP套餐：{package.name}')
        
        return success_response(package.to_dict())
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'更新VIP套餐失败：{str(e)}')

@csrf_exempt
@require_http_methods(["DELETE"])
def vip_package_delete(request, package_id):
    """删除VIP套餐"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找套餐
        try:
            package = VipPackage.objects.get(id=package_id)
        except VipPackage.DoesNotExist:
            return error_response('未找到指定的套餐', 404)
        
        # 删除套餐
        package.delete()
        
        # 记录操作日志
        log_operation(admin_id, 'delete_vip_package', f'删除VIP套餐：{package.name}')
        
        return success_response({'message': '删除成功'})
    except Exception as e:
        return error_response(f'删除VIP套餐失败：{str(e)}')

@require_http_methods(["GET"])
def vip_order_list(request):
    """获取VIP订单列表"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        
        # 获取订单列表
        queryset = VipOrder.objects.all().order_by('-created_at')
        result = paginate_queryset(queryset, page, size)
        
        # 格式化数据
        order_list = [order.to_dict() for order in result['items']]
        
        return success_response({
            'list': order_list,
            'total': result['total'],
            'page': result['page'],
            'size': result['size'],
            'pages': result['pages']
        })
    except Exception as e:
        return error_response(f'获取VIP订单列表失败：{str(e)}')

@require_http_methods(["PUT"])
def vip_order_update(request, order_id):
    """更新VIP订单状态"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找订单
        try:
            order = VipOrder.objects.get(id=order_id)
        except VipOrder.DoesNotExist:
            return error_response('未找到指定的订单', 404)
        
        # 解析请求数据
        data = json.loads(request.body)
        payment_status = data.get('payment_status')
        
        if payment_status not in dict(VipOrder.PAYMENT_STATUS_CHOICES):
            return error_response('无效的支付状态', 400)
        
        # 更新订单状态
        order.payment_status = payment_status
        if payment_status == 'paid':
            order.paid_at = timezone.now()
            # 更新用户VIP状态
            user = order.user
            user.is_vip = True
            user.vip_expire_time = timezone.now() + timezone.timedelta(days=order.package.duration)
            user.save()
        order.save()
        
        # 记录操作日志
        log_operation(admin_id, 'update_vip_order', f'更新VIP订单状态：{order.order_no}')
        
        return success_response(order.to_dict())
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'更新VIP订单失败：{str(e)}')

@require_http_methods(["GET"])
def vip_activation_code_list(request):
    """获取VIP激活码列表"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        
        # 获取激活码列表
        queryset = VipActivationCode.objects.all().order_by('-created_at')
        result = paginate_queryset(queryset, page, size)
        
        # 格式化数据
        code_list = [code.to_dict() for code in result['items']]
        
        return success_response({
            'list': code_list,
            'total': result['total'],
            'page': result['page'],
            'size': result['size'],
            'pages': result['pages']
        })
    except Exception as e:
        return error_response(f'获取VIP激活码列表失败：{str(e)}')

@csrf_exempt
@require_http_methods(["POST"])
def vip_activation_code_create(request):
    """创建VIP激活码"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 解析请求数据
        data = json.loads(request.body)
        vip_type = data.get('vip_type')
        expired_at = data.get('expired_at')
        
        if not vip_type or vip_type not in dict(VipActivationCode._meta.get_field('vip_type').choices):
            return error_response('无效的会员类型', 400)
        
        # 创建激活码
        code = VipActivationCode.generate_code(vip_type)
        if expired_at:
            code.expired_at = datetime.strptime(expired_at, '%Y-%m-%d %H:%M:%S')
            code.save()
        
        # 记录操作日志
        log_operation(admin_id, 'create_vip_activation_code', f'创建VIP激活码：{code.code}')
        
        return success_response({
            'id': code.id,
            'code': code.code,
            'vip_type': code.vip_type,
            'vip_type_display': code.get_vip_type_display(),
            'is_used': code.is_used,
            'used_by': None,
            'used_at': None,
            'created_at': code.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'expired_at': code.expired_at.strftime('%Y-%m-%d %H:%M:%S') if code.expired_at else None
        })
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'创建VIP激活码失败：{str(e)}')

@require_http_methods(["POST"])
def vip_activation_code_batch_create(request):
    """批量创建VIP激活码"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 解析请求数据
        data = json.loads(request.body)
        vip_type = data.get('vip_type')
        count = data.get('count', 1)
        expired_at = data.get('expired_at')
        
        if not vip_type or vip_type not in dict(VipActivationCode._meta.get_field('vip_type').choices):
            return error_response('无效的会员类型', 400)
        
        if count < 1 or count > 100:
            return error_response('批量创建数量必须在1-100之间', 400)
        
        # 批量创建激活码
        codes = []
        for _ in range(count):
            code = VipActivationCode.generate_code(vip_type)
            if expired_at:
                code.expired_at = datetime.strptime(expired_at, '%Y-%m-%d %H:%M:%S')
                code.save()
            codes.append({
                'id': code.id,
                'code': code.code,
                'vip_type': code.vip_type,
                'vip_type_display': code.get_vip_type_display(),
                'is_used': code.is_used,
                'used_by': None,
                'used_at': None,
                'created_at': code.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'expired_at': code.expired_at.strftime('%Y-%m-%d %H:%M:%S') if code.expired_at else None
            })
        
        # 记录操作日志
        log_operation(admin_id, 'batch_create_vip_activation_code', f'批量创建VIP激活码：{count}个')
        
        return success_response({'codes': codes})
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'批量创建VIP激活码失败：{str(e)}')

@require_http_methods(["DELETE"])
def vip_activation_code_delete(request, code_id):
    """删除VIP激活码"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找激活码
        try:
            code = VipActivationCode.objects.get(id=code_id)
        except VipActivationCode.DoesNotExist:
            return error_response('未找到指定的激活码', 404)
        
        # 删除激活码
        code.delete()
        
        # 记录操作日志
        log_operation(admin_id, 'delete_vip_activation_code', f'删除VIP激活码：{code.code}')
        
        return success_response({'message': '删除成功'})
    except Exception as e:
        return error_response(f'删除VIP激活码失败：{str(e)}')

@csrf_exempt
@require_http_methods(['GET'])
def vip_member_list(request):
    """
    获取VIP会员列表
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('size', 10))
        
        # 获取筛选参数
        keyword = request.GET.get('keyword', '')
        vip_type = request.GET.get('vip_type', '')
        is_active = request.GET.get('is_active', '')

        # 构建查询
        queryset = VipMember.objects.all()
        
        # 关键词搜索（用户昵称）
        if keyword:
            queryset = queryset.filter(user__nickname__icontains=keyword)
        
        # 会员类型筛选
        if vip_type:
            queryset = queryset.filter(vip_type=vip_type)
        
        # 会员状态筛选
        if is_active != '':
            is_active_bool = is_active.lower() == 'true'
            queryset = queryset.filter(is_active=is_active_bool)

        # 分页
        result = paginate_queryset(queryset.order_by('-created_at'), page, page_size)
        
        # 格式化数据
        member_list = [member.to_dict() for member in result['items']]
        
        # 记录操作日志
        log_operation(admin_id, 'vip_member_list', f'查看VIP会员列表')

        return success_response({
            'list': member_list,
            'total': result['total'],
            'page': result['page'],
            'size': result['size'],
            'pages': result['pages']
        })
    except Exception as e:
        return error_response(f'获取VIP会员列表失败：{str(e)}')

@csrf_exempt
@require_http_methods(['GET'])
def vip_member_detail(request, member_id):
    """
    获取VIP会员详情
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        member = VipMember.objects.get(id=member_id)
        
        # 记录操作日志
        log_operation(admin_id, 'vip_member_detail', f"查看VIP会员详情 ID:{member_id}")

        return success_response(member.to_dict())
    except VipMember.DoesNotExist:
        return error_response('会员不存在', code=404)

@csrf_exempt
@require_http_methods(['PUT'])
def vip_member_update(request, member_id):
    """
    更新VIP会员信息
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        member = VipMember.objects.get(id=member_id)
        data = json.loads(request.body)
        
        # 更新字段
        if 'vip_type' in data:
            member.vip_type = data['vip_type']
        
        if 'is_active' in data:
            member.is_active = data['is_active']
        
        # 如果更新了会员类型，重新计算结束时间
        if 'vip_type' in data and data['vip_type'] != member.vip_type:
            if data['vip_type'] == 'lifetime':
                member.end_time = None
            else:
                duration_days = 30 if data['vip_type'] == 'month' else 365
                member.end_time = timezone.now() + timezone.timedelta(days=duration_days)
        
        member.save()
        
        # 记录操作日志
        log_operation(admin_id, 'update_vip_member', f"更新VIP会员信息 ID:{member_id}")

        return success_response(member.to_dict())
    except VipMember.DoesNotExist:
        return error_response('会员不存在', code=404)
    except json.JSONDecodeError:
        return error_response('无效的请求数据', code=400)

@csrf_exempt
@require_http_methods(['POST'])
def vip_member_create(request):
    """
    创建VIP会员
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        data = json.loads(request.body)
        user_id = data.get('user_id')
        vip_type = data.get('vip_type')
        
        if not user_id or not vip_type:
            return error_response('用户ID和会员类型不能为空', code=400)
        
        # 检查用户是否存在
        try:
            user = WechatUser.objects.get(id=user_id)
        except WechatUser.DoesNotExist:
            return error_response('用户不存在', code=404)
        
        # 检查用户是否已经是会员
        if VipMember.objects.filter(user=user).exists():
            return error_response('用户已经是会员', code=400)
        
        # 创建会员
        member = VipMember.objects.create(
            user=user,
            vip_type=vip_type,
            is_active=True
        )
        
        # 设置结束时间
        if vip_type != 'lifetime':
            duration_days = 30 if vip_type == 'month' else 365
            member.end_time = timezone.now() + timezone.timedelta(days=duration_days)
            member.save()
        
        # 记录操作日志
        log_operation(admin_id, 'create_vip_member', f"创建VIP会员 用户ID:{user_id} 类型:{vip_type}")

        return success_response(message='创建成功')
    except json.JSONDecodeError:
        return error_response('无效的请求数据', code=400)

@csrf_exempt
@require_http_methods(['DELETE'])
def vip_member_delete(request, member_id):
    """
    删除VIP会员
    """
    # 验证token
    token = request.headers.get('Authorization')
    admin_id = verify_token(token)
    if not admin_id:
        return error_response('未授权访问', code=401)

    try:
        member = VipMember.objects.get(id=member_id)
        member.delete()
        
        # 记录操作日志
        log_operation(admin_id, 'delete_vip_member', f"删除VIP会员 ID:{member_id}")

        return success_response(message='删除成功')
    except VipMember.DoesNotExist:
        return error_response('会员不存在', code=404) 
    